package cn.kmsoft.common.utils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * ini文件通用方法
 *
 * @author yanggy
 * @version 0.1
 * @time 2015-7-2 上午9:39:19
 */
public final class IniUtil {
    // 注释正则表达式
    private static final Pattern COMMENT_PATTERN = Pattern.compile("^\\s*#.*");
    // 分组正则表达式
    private static final Pattern GROUP_PATTERN = Pattern.compile("^\\s*\\[[^\\]]+\\]\\s*$");
    // 键值对正则表达式
    private static final Pattern KEYVALUE_PATTERN = Pattern.compile("^\\s*[^=]{1}.*=.*$");

    /**
     * 加载ini文件
     *
     * @param path 文件路径
     * @return {Map}
     * @throws IOException
     */
    public static Map<String, Map<String, String>> load(String path) throws IOException {
        FileInputStream inputStream = new FileInputStream(path);
        InputStreamReader streamReader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader reader = new BufferedReader(streamReader);

        Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
        String line;
        String group = "";    // 上一个分组
        Map<String, String> keyvalues = null;

        while ((line = reader.readLine()) != null) {
            line = line.trim();

            if (StringUtil.isNullOrEmpty(line) || isComment(line)) {
                continue;    // 跳过注释和空行
            }
            if (isGroup(line)) {
                if (!group.equals("")) {
                    map.put(group, keyvalues);
                }
                group = getGroupName(line);    // 覆盖当前分组名称
                keyvalues = new HashMap<String, String>();    // 初始化新分组的键值对
            } else if (isKeyValue(line)) {
                if (!group.equals("") && keyvalues != null) {
                    String[] kv = getKeyValue(line);
                    keyvalues.put(kv[0], kv[1]);
                }
            }
        }
        // 加入最后一个分组
        if (!group.equals("") && !map.containsKey(group) && keyvalues != null) {
            map.put(group, keyvalues);
        }
        reader.close();
        return map;
    }

    /**
     * 是否为注释(以#开头的行作为注释)
     *
     * @param line
     * @return
     */
    private static boolean isComment(String line) {
        return COMMENT_PATTERN.matcher(line).matches();
    }

    /**
     * 是否为分组(包含在[]中的作为分组)
     *
     * @param line
     * @return
     */
    private static boolean isGroup(String line) {
        return GROUP_PATTERN.matcher(line).matches();
    }

    /**
     * 取得分组名称
     *
     * @param line
     * @return
     */
    private static String getGroupName(String line) {
        return line.substring(1, line.length() - 1);
    }

    /**
     * 是否为键值对(格式: Key=Value)
     *
     * @param line
     * @return
     */
    private static boolean isKeyValue(String line) {
        return KEYVALUE_PATTERN.matcher(line).matches();
    }

    /**
     * 获取键值对
     *
     * @param line
     * @return
     */
    private static String[] getKeyValue(String line) {
        int equalIndex = line.indexOf("=");
        String key = line.substring(0, equalIndex).trim();
        String value = line.substring(equalIndex + 1).trim();
        return new String[]{key, value};
    }
}
